package com.springboot.learn_web_rabbitmq.demo2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeoutException;

public class Customer2 {
    private static final String QUEUE_NAME="QUEUE_TEST2";
    public static void main(String[] args) throws IOException, TimeoutException {
        // 区分不同工作进程的输出
        int hashCode = Thread.currentThread().hashCode();
        // 创建连接和频道
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 声明队列、设置队列持久化
        boolean durable = true;
        channel.queueDeclare(QUEUE_NAME, durable, false, false, null);
        System.out.println(hashCode + " [*] Waiting for messages. To exit press CTRL+C");

        //设置最大服务转发消息数量, 公平转发
        int prefetchCount = 1;
        channel.basicQos(prefetchCount);

        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body,"UTF-8");
                try {
                    System.out.println(hashCode + " [x] Received '" + message + "'");
                    doWork(message);
                    System.out.println(hashCode + " [x] Done");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        // 指定消费队列，打开应答机制, 注意false才是打开手动应对
        boolean ack = false ;
        channel.basicConsume(QUEUE_NAME, ack, consumer);
    }
    /**
     * 每个点耗时1s
     *
     * @param task
     * @throws InterruptedException
     */
    private static void doWork(String task) throws InterruptedException {
        for (char ch : task.toCharArray()) {
            if (ch == '.')
                Thread.sleep(1000);
        }
    }
}
